<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <el-checkbox-group v-model="selectList">
      <div
        class="vc-image-list"
        :style="visual.parseStyle(currNode.currCompStyle)"
      >
        <div
          v-for="(data, index) in checkDataList"
          :key="index"
          class="vc-image-item"
          :style="itemStyle"
        >
          <el-image
            v-if="data['图片']"
            preview-teleported
            hide-on-click-modal
            :src="imageUrl + data['图片']"
            :preview-src-list="[imageUrl + data['图片']]"
            style="width:100%;height:100%"
            :fit="imageFit"
          />
          <div :style="checkboxStyle">
            <el-checkbox
              v-if="showCheckbox"
              :key="data.tempUuid"
              :value="data.tempUuid"
            ></el-checkbox>
          </div>
        </div>
      </div>
    </el-checkbox-group>
  </div>
  <div
    v-if="initializing"
    v-loading="true"
    element-loading-text=""
    style="min-height: 30px;"
  ></div>
</template>

<script setup>
import { ref, nextTick, inject, getCurrentInstance, onMounted, computed, watch, onUnmounted } from 'vue';
import visual from "@/visual/js/visual";
import tool from "@/utils/tool";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object,
  inputParam: Object
});
const currNode = ref(props.node);
const dataList = ref([{}]);
const imageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const showCheckbox = ref(false);
const checkboxStyle = ref('');
const selectList = ref([]);
const itemStyle = ref('');
const imageFit = ref('cover');
const initializing = ref(true);
const compStyle = ref({});
const minSelect = ref(0);
const maxSelect = ref(0);
const pageData = inject('pageData', null);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  compStyle.value = currNode.value.currCompStyle || {};
  showCheckbox.value = compStyle.value['checkbox'] || false;
  checkboxStyle.value = 'position: absolute;' + (compStyle.value['checkbox.position'] || '');
  minSelect.value = parseInt(compStyle.value['min-select'] || '0');
  maxSelect.value = parseInt(compStyle.value['max-select'] || '0');
  initItemStyle();
  await nextTick(() => initializing.value = false);
};

const loadDataList = tool.debounce(async() => {
  initializing.value = true;
  dataList.value = (await visual.loadData(
    currNode.value.compData,
    eventHandler,
    getData(),
    currNode.value)).data || [];
  await nextTick(() => initializing.value = false);
});

const initItemStyle = () => {
  itemStyle.value = 'position: relative;';
  imageFit.value = compStyle.value['image.fit'] || 'cover';
  itemStyle.value += 'width: ' + compStyle.value['image.width'] + ';';
  itemStyle.value += 'height: ' + compStyle.value['image.height'] + ';';
  return itemStyle.value;
};

const checkDataList = computed(() => {
  dataList.value.forEach(data => {
    data.tempUuid = tool.uuids();
  })
  return dataList.value;
});

const getData = () => {
  const resultList = [];
  selectList.value.forEach(tempUuid => {
    const find = dataList.value.find(item => item.tempUuid === tempUuid);
    if (find) {
      const result = tool.deepClone(find);
      delete result['tempUuid'];
      resultList.push(result);
    }
  });
  return {
    inputParam: currNode.value.inputParam || {},
    dataList: resultList
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const validate = (callback) => {
  const promise = new Promise((resolve, reject) => {
    const selectCount = selectList.value.length;
    if (minSelect.value > 0 && selectCount < minSelect.value) {
      reject(new Error("最少选择 " + minSelect.value + " 张图片！"));
    }
    if (maxSelect.value > 0 && selectCount > maxSelect.value) {
      reject(new Error("最多只能选择 " + maxSelect.value + " 张图片！"));
    }
    resolve(true);
  });
  promise.then(valid => callback(valid));
  return promise;
};

watch(() => selectList.value, (list) => {
  const resultList = [];
  list.forEach(tempUuid => {
    const find = dataList.value.find(item => item.tempUuid === tempUuid);
    if (find) {
      const result = tool.deepClone(find);
      delete result['tempUuid'];
      resultList.push(result);
    }
  });
  pageData.value[currNode.value.name] = resultList;
});

const refresh = async() => {
  initializing.value = true;
  loadDataList();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  loadDataList();
  await eventHandler.trigger('初始化事件');
});

onUnmounted(() => {
  eventHandler.unregister();
});

defineExpose({ getData, changeStyle, validate, refresh });
</script>

<style scoped>
.vc-image-item {
  :deep() {
    .el-checkbox {
      height: 14px!important;
    }
    .el-checkbox__label {
      padding-left: 0!important;
    }
  }
}
</style>